package com.itcast.controller;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itcast.health.pojo.MemberByTime;
import com.itcast.health.pojo.Result;
import com.itcast.service.ReportService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

import static cn.hutool.core.date.DateUtil.offsetMonth;

/**
 * @author: lei
 * @version: V1.0
 * @date: 2019/11/30 16:05
 * @description: com.itheima.controller
 * 报表数据查询的controller
 */
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    ReportService reportService;


    @RequestMapping("/getMemberReport")
    public Result getMemberReport(@RequestBody MemberByTime m){
//创建一个集合,保存所有的月份
        List<String> months = new ArrayList<>();
        ObjectUtil.isNull(m);
        Date start = m.getStart();
        Date end = m.getEnd();
        String endStr="";
        //默认查询12个月
        long month = 12;
        //获取过去一年的月份
        DateTime dateTime = offsetMonth(new Date(), -12);
        //如果页面传了就使用页面时间
        if (null != start && null != end) {
            month = DateUtil.betweenMonth(start, end, false);
            dateTime = DateTime.of(start);
            //转换日期格式,根据时间段查询时,需要最后一个时间
            endStr = DateUtil.format(end, "yyyy-MM-dd");
        }
        String monthStr="";
        for (int i = 0; i <month+1 ; i++) {
            if (month == 12) {
                monthStr = offsetMonth(dateTime, i).toString("yyyy-MM");
                monthStr = monthStr + "-31";
                months.add(monthStr);
            } else {
                if (i == month) {
                    monthStr = endStr;
                    months.add(monthStr);
                    break;
                }
                monthStr = offsetMonth(dateTime, i).toString("yyyy-MM-dd");
                months.add(monthStr);
            }
        }


        List<Integer> memberCount = reportService.getMemberReport(months);
        //创建一个map,用于封装数据,返回给前端
        Map map = new HashMap();
        map.put("months", months);
        map.put("memberCount", memberCount);
        return Result.success("", map);
    }



    /**
     * 报表男女会员的人数查询作为扇形图
     * @return
     */
    @RequestMapping("/getMemberProportion")
    public Result getMemberProportion(){
         List<Map> list=reportService.getSexAndCount();
         List<Map> mapList = reportService.getAgeAndCount();
         Map<String,List<Map>> map = new HashMap<>();
         map.put("list",list);
         map.put("mapList",mapList);
         return new Result(true,"",map);
    }

}
